// pages/shopInformation/shopInformation.js
const app = getApp();
import httpsUtils from '../../utils/https.js';

var rate = 0; //分辨转换
var floatTop = 0; //悬浮高度
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 店铺信息
    shopId: '',
    shopInfo: {},
    dataImg: [],
    // small_nav初始数据
    tabs: [
      { id: "nav_1", isSelect: true, title: "全部", value: 1, isFirst: false },
      { id: "nav_2", isSelect: false, title: "推荐", value: 2, isFirst: true },
      { id: "nav_3", isSelect: false, title: "热卖", value: 3, isFirst: true },
      { id: "nav_4", isSelect: false, title: "保版", value: 4, isFirst: true },
      { id: "nav_5", isSelect: false, title: "尾货", value: 5, isFirst: true }
    ], //tabbar数组
    allList: [],//全部数据
    allLenght: 1,
    allCurrent: 1,
    allHasNextPage: true,

    newsList: [],//上新
    newsLength: 1,
    newsCurrent: 1,
    newsHasNextPage: true,

    hotList: [],//热卖
    hotLength: 1,
    hotCurrent: 1,
    hotHasNextPage: true,

    vipList: [],//会员
    vipLength: 1,
    vipCurrent: 1,
    vipHasNextPage: true,

    stocList: [],//尾货
    stocLength: 1,
    stocCurrent: 1,
    stocHasNextPage: true,

    curTabId: "nav_1", //当前tabid
    isShowFloatTab: false, //是否显示悬浮tab

    levelType: 0,//默认0表示星星，1表示钻石，2表示皇冠
    levelArray: [1],//默认0

    focusStatus: 2,//默认2表示不关注 1表示关注

    bullInfo: null
  },

 
  call: function () {
    if (this.data.shopInfo.phone == null) {
      wx.showToast({
        title: '暂无联系方式',
      })
      return;
    }
    wx.makePhoneCall({
      phoneNumber: this.data.shopInfo.phone,
      success: function () {

      },
      fail: function () {
        wx.showToast({
          title: '拨打失败',
        })
      }
    })
  },
  /**
 * 跳转首页
 */
  toindex: function () {
    var pages = getCurrentPages();
    if (pages.length >= 2) {
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.switchTab({
        url: '../index/index',
      })
    }  
  },

  /**
   * 采购商信息
   */
  getBullInfo: function () {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/bullInfo/selectOne1',
      data: {},
    }, function (json) {
      wx.setStorageSync("bullInfo", json.data)
      if (json.data && json.success) {
        that.setData({
          bullInfo: json.data.status,
        })
      }
    })
  },

  /**
   * 等级转换
   */
  shopGrade: function (creditLevel) {
    var that = this;
    var levelType = parseInt(creditLevel / 5);
    var levelTimes = parseInt(creditLevel % 5);
    var levelArray = [];
    for (var i = 0; i < levelTimes; i++) {
      levelArray.push(levelType);
    }
    that.setData({
      levelType: levelType,
      levelArray: levelArray
    })
  },
  /**
  * 关注或取消关注
  */
  updateFocusShop: function () {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/focusShop/updateOrAdd?shopId=' + that.data.shopId,
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        if (json.data.status == 1) {
          wx.showToast({
            title: '关注成功',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: '取消关注成功',
            icon: 'none'
          })
        }
        that.setData({
          focusStatus: json.data.status,
        })
      }
      if (json.success == false && json.code == 'OVERTIME') {
        wx.navigateTo({
          url: '../wxLogin/wxLogin?type=3&isTab=false',
        })
      }
    })
  },
  /**
   * 店铺是否关注
   */
  getFocusShop: function () {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/shopInfo/isFocusShop?id=' + that.data.shopId,
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        that.setData({
          focusStatus: json.data.status,
        })
      }
    })
  },
  /**
   * 店铺信息数据加载
   */
  getShopInfo: function () {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/shopInfo/selectagno1?shopId=' + that.data.shopId,
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        wx.setStorageSync("shopInfo", json.data)
        var imgUrls = [];
        if (json.data.storeImg != null) {
          imgUrls = json.data.storeImg.split("***");
        }
        //设置等级
        that.shopGrade(json.data.creditLevel);

        that.setData({
          shopInfo: json.data,
          dataImg: imgUrls,
        })

        if (json.data.status == 4) {
          wx.showModal({
            title: '提示',
            content: '非常抱歉！该店铺已暂停营业',
            showCancel: false
          })
        }
      } else {
        console.log("请求失败")
      }
    })
  },
  /**
   * 获取商品详情
   */
  gotoDetail: function (e) {
    var that = this;
    var goodsId = e.currentTarget.dataset.goodsid;
    var formatCare = e.currentTarget.dataset.goodscare;
    var userInfo = wx.getStorageSync("userInfo")
    if (formatCare == 1 && that.data.bullInfo == null && userInfo.id != that.data.shopInfo.userId) {
      wx.showModal({
        title: '提示',
        content: '查看保版商品，请下载服装基地APP后查看',
        showCancel:false        
      })
    } else {
      wx.navigateTo({
        url: '../productDetail/productDetail?shareType=3&id=' + goodsId,
      })
    }
  },
  /**
   * 获取店铺商品
   */
  getShopGoods: function (e) {
    wx.showToast({
      title: '加载中...',
      icon: 'loading'
    })
    var that = this;
    var nowTab = 1;
    for (let obj of that.data.tabs) {
      if (obj.isSelect) {
        nowTab = obj.value;
      }
    }

    var shopId = that.data.shopId;
    var goodsType = '';
    var sort = '';
    var formatCare = '';
    var current = 1;

    //全部
    if (nowTab == 1) {
      goodsType = '';
      sort = 2;
      current = that.data.allCurrent
    }
    //推荐
    if (nowTab == 2) {
      goodsType = 1;
      sort = '';
      current = that.data.newsCurrent
    }
    //热卖
    if (nowTab == 3) {
      goodsType = 3;
      sort = '';
      current = that.data.hotCurrent
    }
    //保版
    if (nowTab == 4) {
      goodsType = '';
      sort = '';
      formatCare = 1;
      current = that.data.vipCurrent
    }
    //尾货
    if (nowTab == 5) {
      goodsType = 5;
      sort = '';
      current = that.data.stocCurrent
    }

    that.getData({
      _url: app.globalData._url + '/goods/selectGoodsList?shopId=' + shopId + "&goodsType=" + goodsType + "&sort=" + sort + "&formatCare=" + formatCare + "&current=" + current,
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        //全部
        if (nowTab == 1) {
          var allList = json.data.list;
          var userInfo = wx.getStorageSync("userInfo");
          for (let obj of allList) {
            if (obj.formatCare == 1 && that.data.bullInfo == null && userInfo.id != that.data.shopInfo.userId) {
              obj.coverUrl = obj.coverUrl + '?x-oss-process=image/blur,r_50,s_50'
            }
          }
          that.setData({
            allList: that.data.allList.concat(json.data.list),
            allLenght: json.data.total,
            allCurrent: json.data.pageNum,
            allHasNextPage: json.data.hasNextPage,
          })
        }
        //推荐
        if (nowTab == 2) {
          that.setData({
            newsList: that.data.newsList.concat(json.data.list),
            newsLength: json.data.total,
            newsCurrent: json.data.pageNum,
            newsHasNextPage: json.data.hasNextPage,
          })
        }
        //热卖
        if (nowTab == 3) {
          that.setData({
            hotList: that.data.hotList.concat(json.data.list),
            hotLength: json.data.total,
            hotCurrent: json.data.pageNum,
            hotHasNextPage: json.data.hasNextPage,
          })
        }
        //保版
        if (nowTab == 4) {
          var vipList = json.data.list;
          var userInfo = wx.getStorageSync("userInfo")
          if (that.data.bullInfo == null && userInfo.id != that.data.shopInfo.userId) {
            for (let obj of vipList) {
              obj.coverUrl = obj.coverUrl + '?x-oss-process=image/blur,r_50,s_50'
            }
          }

          that.setData({
            vipList: that.data.vipList.concat(json.data.list),
            vipLength: json.data.total,
            vipCurrent: json.data.pageNum,
            vipHasNextPage: json.data.hasNextPage,
          })
        }
        //尾货
        if (nowTab == 5) {
          that.setData({
            stocList: that.data.stocList.concat(json.data.list),
            stocLength: json.data.total,
            stocCurrent: json.data.pageNum,
            stocHasNextPage: json.data.hasNextPage,
          })
        }

      } else {
        console.log("请求失败")
      }
      wx.hideToast();
    })
  },
  /**
   * 下拉刷新
   */
  goodPullDown: function () {
    var that = this;
    var nowTab = 1;
    for (let obj of that.data.tabs) {
      if (obj.isSelect) {
        nowTab = obj.value;
      }
    }
    //全部
    if (nowTab == 1) {
      if (that.data.allHasNextPage) {
        that.setData({
          allCurrent: that.data.allCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //推荐
    if (nowTab == 2) {
      if (that.data.newsHasNextPage) {
        that.setData({
          newsCurrent: that.data.newsCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //热卖
    if (nowTab == 3) {
      if (that.data.hotHasNextPage) {
        that.setData({
          hotCurrent: that.data.hotCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //保版
    if (nowTab == 4) {
      if (that.data.vipHasNextPage) {
        that.setData({
          vipCurrent: that.data.vipCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //尾货
    if (nowTab == 5) {
      if (that.data.stocHasNextPage) {
        that.setData({
          stocCurrent: that.data.stocCurrent + 1,
        })
        that.getShopGoods();
      }
    }
  },
  //店铺档案跳转
  backFont: function () {
    var that = this;
    wx.navigateTo({
      url: `../storeManges/storeManges?shopId=${that.data.shopId}`
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      shopId: options.shopid,
    })

    //店铺信息
    that.getShopInfo();

    //商品信息
    that.getShopGoods();

    //关注
    that.getFocusShop();

    /** small nav */
    that.getScrollTop();

    /**
     * 采购商
     */
    that.getBullInfo();
  },
  // 事件函数

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (app.globalData.isFlush == true) {
      //是否关注店铺
      that.getFocusShop();
      app.globalData.isFlush = false;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      // 店铺信息
      shopInfo: {},
      dataImg: [],
      allList: [],//全部数据
      allLenght: 1,
      allCurrent: 1,
      allHasNextPage: true,

      newsList: [],//上新
      newsLength: 1,
      newsCurrent: 1,
      newsHasNextPage: true,

      hotList: [],//热卖
      hotLength: 1,
      hotCurrent: 1,
      hotHasNextPage: true,

      vipList: [],//会员
      vipLength: 1,
      vipCurrent: 1,
      vipHasNextPage: true,

      stocList: [],//尾货
      stocLength: 1,
      stocCurrent: 1,
      stocHasNextPage: true,

      levelType: 0,//默认0表示星星，1表示钻石，2表示皇冠
      levelArray: [1],//默认0

      focusStatus: 2,//默认2表示不关注 1表示关注

      bullInfo: null
    })

    //店铺信息
    that.getShopInfo();

    //商品信息
    that.getShopGoods();

    //关注
    that.getFocusShop();

    /** small nav */
    that.getScrollTop();

    /**
     * 采购商
     */
    that.getBullInfo();

    wx.stopPullDownRefresh(); 
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    //下拉刷新
    this.goodPullDown();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.shopInfo.storeName,
      path: '/pages/shopInformation/shopInformation?shopid=' + this.data.shopInfo.id,
    }
  },
  // small nav
  /**
   * 获得滑动导致悬浮开始的高度
   * @return {[type]} [description]
   */
  getScrollTop: function () {
    var that = this;
    if (wx.canIUse('getSystemInfo.success.screenWidth')) {
      wx: wx.getSystemInfo({
        success: function (res) {
          rate = res.screenWidth / 750;
          floatTop = 410 * rate;
          that.setData({
            scrollTop: 410 * res.screenWidth / 750,
            scrollHeight: res.screenHeight / (res.screenWidth / 750) - 128,
          });
        }
      });
    }
  },
  /**
    * 生命周期函数--监听页面加载
    */
  onPageScroll: function (event) {
    var scrollTop = event.scrollTop;
    if (scrollTop >= floatTop && !this.data.isShowFloatTab) {
      this.setData({
        isShowFloatTab: true,
      });
    } else if (scrollTop < floatTop && this.data.isShowFloatTab) {
      this.setData({
        isShowFloatTab: false,
      });
    }
  },

  /**
     * 点击tab切换
     * @param  {[type]} event 
     * @return {[type]}       
     */
  clickTab: function (event) {
    var id = event.detail.id;
    this.data.curTabId = id;
    var isFirst = true;
    for (var i = 0; i < this.data.tabs.length; i++) {
      if (id == this.data.tabs[i].id) {
        isFirst = this.data.tabs[i].isFirst
        this.data.tabs[i].isSelect = true;
        this.data.tabs[i].isFirst = false;
      } else {
        this.data.tabs[i].isSelect = false;
      }
    }
    this.setData({
      tabs: this.data.tabs,
      curTabId: this.data.curTabId,
    });
    //更新数据，第一次点击时候加载重新加载数据
    if (isFirst) {
      this.getShopGoods();
    }

  },
  getData: function (params, cb) {
    wx.request({
      url: params._url,
      data: params.data,
      method: 'GET',
      header: {
        'content-type': 'application/json;charset=UTF-8'
      },
      success: function (res) {
        if (res.statusCode == 200) {
          typeof cb === 'function' && cb(res.data)
        }
      },
      fail: function () {
      },
      complete: function () {
      }
    })
  }
})